<template>
	<view class="main-content">
		<MHeader>{{ state.pageName }}</MHeader>
		<scroll-view scroll-y="true" style="height: calc(100% - 180rpx)">
			<view>
				<item name="组织" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_ORGName"  placeholder="请选择" @click.native="choose('ORG_Organizations', 'F_QUQY_OrgId', 'FNumber', 'F_QUQY_ORGName', 'FNumber', 'FName')" />
				</item>
				<item name="日期" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Date"  @click="chooseT('F_QUQY_Date')" placeholder="请选择" />
				</item>
				<item name="养殖批次" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BreedingContractName"  placeholder="请选择" @click.native="choose('BAS_PreBaseDataOne', 'F_QUQY_BreedingContract', 'FNUMBER', 'F_QUQY_BreedingContractName', 'FNumber', 'FName')" />
				</item>
				<item name="是否内部采购" must>
					<van-switch v-model="state.info.Data.Model.F_QUQY_InternalPur" size="24"></van-switch>
				</item>
				<item name="申请司机" sign must>
					<input class="input"  v-model="state.info.Data.Model.F_QUQY_PullingDriverName" placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo', 'F_QUQY_PullingDriver', 'FNUMBER', 'F_QUQY_PullingDriverName', 'FNumber', 'FName')" />
				</item>
				<item name="拉料司机" sign must>
					<input class="input"  v-model="state.info.Data.Model.F_QUQY_PullingDriver1Name" placeholder="请选择" @click.native="choose('BAS_PreBaseDataTwo', 'F_QUQY_PullingDriver1', 'FNUMBER', 'F_QUQY_PullingDriver1Name', 'FNumber', 'FName')" />
				</item>
				<item name="饲料供应商" sign must>
					<input class="input"  v-model="state.info.Data.Model.F_QUQY_FeedSupplierName" placeholder="请选择" @click.native="choose('BD_Supplier', 'F_QUQY_FeedSupplier', 'FNUMBER', 'F_QUQY_FeedSupplierName', 'FNumber', 'FName','102814,109470,109471')" />
				</item>
			</view>
			<MHeader hidTag>
				<van-icon name="cluster" color="#1989fa" style="margin-right: 10rpx" />
				饲料列表
				<template #right>
					<van-icon name="add-o" size="20" @click="appendItem" />
				</template>
			</MHeader>
			<view style="padding-bottom: 10rpx">
				<view class="card" v-for="(item, index) in state.info.Data.Model.FEntity">
					<view class="card-index">{{ index + 1 }}</view>
					<item name="物料" sign must @longpress="longpress(item, index)">
						<input class="input" v-model="item.F_QUQY_MaterialName"  placeholder="请选择" @click.native="choose('BD_MATERIAL', 'F_QUQY_Material', 'FNUMBER', 'F_QUQY_MaterialName', 'FNumber', 'FName', '101190,101191,101192,101193',null,item)" />
					</item>
					<item name="库存单位">
						<input class="input" v-model="item.F_QUQY_UnitIDName" disabled placeholder="自动带出" />
					</item>
					<van-field v-model="item.F_RSUS_sendQty" type="number" label="实发数量(袋)" placeholder="请输入" input-align="right"/>
					<van-field v-model="item.F_QUQY_Price" type="number" label="单价" placeholder="请输入" input-align="right">
						<template #extra>
							<text class="field-Input-Right-Text">元</text>
						</template>
					</van-field>
					<van-field v-model="item.F_QUQY_UnitPrice" type="number" label="含税单价" placeholder="请输入" input-align="right">
						<template #extra>
							<text class="field-Input-Right-Text">元</text>
						</template>
					</van-field>
					<van-field v-model="item.F_QUQY_TaxAmount" type="number" label="税额" placeholder="请输入" input-align="right"/>
					<van-field v-model="item.F_QUQY_TotalTaxAmount" type="number" label="价税合计" placeholder="请输入" input-align="right">
						<template #extra>
							<text class="field-Input-Right-Text">元</text>
						</template>
					</van-field>
					<item name="仓库名称">
						<input class="input" v-model="item.F_QUQY_WarehouseName" disabled placeholder="仓库自动带出" />
					</item>
					<van-field v-model="item.F_QUQY_CanOutQty" type="number" label="剩余可出库数量" placeholder="请输入" input-align="right"/>
	<!-- 				<item name="采购成本价">
						<input class="input" v-model="item.F_QUQY_PurchaseCostPrice" type="number" placeholder="请输入" style="padding-right: 35rpx" />
						<text class="symbol">元</text>
					</item> -->
					<!-- <item name="金额">
						<input class="input" v-model="item.F_QUQY_Amount" type="number" placeholder="请输入" style="padding-right: 35rpx" />
						<text class="symbol">元</text>
					</item> -->
					<van-field v-model="item.F_QUQY_Amount" type="number" label="金额" placeholder="请输入" input-align="right">
						<template #extra>
							<text class="field-Input-Right-Text">元</text>
						</template>
					</van-field>
				</view>
			</view>
		</scroll-view>
		<SubmitBtn name="保 存" @submit="save"></SubmitBtn>
	</view>
	<ChooseTime ref="chooseTime" />
</template>

<script setup>
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref, watch, nextTick } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import { confirm, msg } from '/utils/utils.js'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		info: {
			FormId: 'QUQY_SalesDeliveryOrder',
			Data: {
				Model: {
					F_QUQY_InternalPur: false,
					FEntity: [],
					F_QUQY_OrgId: {
						FNumber: null
					},
					F_QUQY_BreedingContract: {
						FNUMBER: null
					},
					F_QUQY_PullingDriver: {
						FNUMBER: null
					},
					F_QUQY_PullingDriver1: {
						FNUMBER: null
					},
					F_QUQY_FeedSupplier: {
						FNUMBER: null
					}
				}
			}
		},
		rules: {
			F_QUQY_ORGName: '请选择组织！',
			F_QUQY_Date: '请选择日期！',
			F_QUQY_BreedingContractName: '请选择养殖批次！',
			F_QUQY_PullingDriverName: '请选择申请司机！',
			F_QUQY_PullingDriver1Name: '请选择拉料司机！',
			F_QUQY_FeedSupplierName: '请选择供应商！'
		},
		pageName: '饲料出库',
		FilterStringAboutOrg: []
	})

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName)
	}

	// 不好，参数太多 -。-
	// 1.组织控制（使用组织为当前选择的组织）：养殖户、司机
	// 2.业务员、技术员要审核过的
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther, row) => {
		// 🐟 查询条件
		let FilterString = []
		// 🐟 选择组织前
		if (Field == 'F_QUQY_OrgId') {

		}

		// 🐟 1
		let mustHasOrg = ['F_QUQY_BreedingContract', 'F_QUQY_FeedSupplier', 'F_QUQY_Material']
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_ORGName) return msg('请先选择组织！')
			FilterString = state.FilterStringAboutOrg
		}

		uni.navigateTo({
			url: `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择`,
			success: res => { res.eventChannel.emit('fun', [fun, FilterString]) }
		})

		// 回调方法
		let fun = (list) => {
			if (Field == 'F_QUQY_Material') {
				// 🍕 子集里的
				row[Field][FieldSon] = list[0][IdKey]
				row[FieldName] = list[0][IdKeyName]
				// 🍕 查询物料库存单位，不传，后端自动带出
				kdApis.formQuery({
					data: {
						FormId: 'BD_UNIT',
						FieldKeys: 'FName,FNumber,FUNITID',
						FilterString: [{ "Left": "(", "FieldName": "FUNITID", "Compare": "=", "Value": list[0].FStoreUnitID, "Right": ")", "Logic": "and" }]
					}
				}).then(res => {
					if (res && res.length) {
						row.F_QUQY_UnitIDName = res[0].FName
					}
				})
				// 🍕 查询仓库
				kdApis.formQuery({
					data: {
						FormId: 'BD_STOCK',
						FieldKeys: 'FName,FNumber,FStockId',
						FilterString: [{ "Left": "(", "FieldName": "FStockId", "Compare": "=", "Value": list[0].FStockId, "Right": ")", "Logic": "and" }]
					}
				}).then(res => {
					if (res && res.length) {
						// row.F_QUQY_UnitIDName = res[0].FName
					}
				})
				// list[0].FStoreUnitID
			} else {
				state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
				state.info.Data.Model[FieldName] = list[0][IdKeyName]
				if (BringOther) {
					state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]
				}
			}


			// 🐟 选择组织后
			if (Field == 'F_QUQY_OrgId') {
				// 🍕 填充查询条件
				state.FilterStringAboutOrg = [{ "Left": "(", "FieldName": "FUseOrgId", "Compare": "=", "Value": list[0].FOrgID, "Right": ")", "Logic": "and" }]

				// 🍕 初始化 养殖批次等字段及其带出的字段
				for (let key in state.info.Data.Model) {
					let value = state.info.Data.Model[key]
					if (mustHasOrg.includes(key) && value) {
						if (typeof(value) === 'object') {
							for (let k in value) { value[k] = null }
							state.info.Data.Model[`${key}Name`] = null
							if (state.info.Data.Model[`${key}TEM`]) state.info.Data.Model[`${key}TEM`] = null // 带出的字段
						} else {
							value = null
						}
					}
				}
			}
		}
	}

	const appendItem = () => {
		let obj = {
			F_QUQY_Material: {
				FNUMBER: null
			},
			// F_QUQY_Warehouse: {
			// 	FNUMBER: null
			// },
			// F_QUQY_WarehouseName: null,
			F_QUQY_UnitIDName: null,
			// F_QUQY_CanOutQty: null,
			// F_RSUS_sendQty: null,
			// F_QUQY_PurchaseCostPrice: null,
			// F_QUQY_UnitPrice: null,
			// F_QUQY_TotalTaxAmount: null,
			// F_QUQY_Price: null,
			// F_QUQY_Amount: null,
			// F_QUQY_TaxAmount: null
		}
		state.info.Data.Model.FEntity.push(obj)
	}

	const longpress = (item, index) => {
		let msg = item.F_QUQY_MaterialName ? `请确认删除 [ ${item.F_QUQY_MaterialName} ] ？` : '请确认删除 ？'
		confirm(msg).then(() => {
			state.info.Data.Model.FEntity.splice(index, 1)
		}).catch(() => {})
	}

	const save = async () => {
		await checkForm(state.info.Data.Model, state.rules)
		kdApis.formSave(state.info).then(res => {
			if (res) {
				msg('保存成功！')
				setTimeout(() => {
					uni.navigateBack()
				}, 300)
			}
		})
	}
	const getDetails = (Id) => {
		kdApis.formView({
			formId: 'QUQY_SalesDeliveryOrder',
			data: { Id }
		}).then((res) => {
			if (res) {
				state.FilterStringAboutOrg = [{ Left: '(', FieldName: 'FUseOrgId', Compare: '=', Value: res.F_QUQY_ORGID_Id, Right: ')', Logic: 'and' }]
				let obj = {
					FBillNo: res.FBillNo,
					F_QUQY_BreedingContractName: res.F_QUQY_BREEDBATCH,
					F_QUQY_FeedApplication: res.F_QUQY_FeedApplication,
					F_QUQY_PullingDriver1Name: res.F_QUQY_PullingDriver1Name,
					F_QUQY_FeedSupplierName: res.F_QUQY_FeedSupplierName,
					F_QUQY_ORGName: res.F_QUQY_ORGName,
					F_QUQY_Date: moment(res.F_QUQY_Date).format('YYYY-MM-DD'),
					F_QUQY_InternalPur: res.F_QUQY_InternalPur == 'true' ? '是' : '否',
					FEntity: res.FEntity
				}
			}
		})
	}
	onLoad(async (query) => {
		if (query.Id) {
			state.pageName = '饲料出库编辑'
			getDetails(query.Id)
		}
	})
</script>
<style lang="scss" scoped>
	.card {
		position: relative;
		width: calc(100% - 60rpx);
		margin: 20rpx auto;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;

		.card-index {
			position: absolute;
			display: flex;
			// align-items: center;
			// justify-content: center;
			width: 40rpx;
			height: 40rpx;
			padding-left: 10rpx;
			font-size: 24rpx;
			background: #409eff;
			color: #fff;
			clip-path: polygon(0 0, 0 40rpx, 10rpx 40rpx, 40rpx 10rpx, 40rpx 0);
		}
	}
</style>